package cn.controller;

import java.io.IOException;
import java.math.BigDecimal;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.domain.TbProduct;
import cn.domain.TbProductExample;
import cn.service.TbProductService;

@Controller
public class ProductController {
	
	@Autowired
	TbProductService service;
	
	@RequestMapping("/show.action")
	public String show(Model model,@RequestParam(value="pn",defaultValue="1")Integer pn) {
		TbProductExample example=new TbProductExample();
		example.createCriteria();
		int pageSize=8;
		PageHelper.startPage(pn, pageSize);
		PageInfo<TbProduct> page=new PageInfo<>(service.selectByExample(example), 5);
		model.addAttribute("page", page);
		return "/product/show.jsp";
	}
	
	@RequestMapping("/insert.action")
	public String insert(TbProduct product) {
		@SuppressWarnings("unused")
		int result=service.insert(product);		
		return "forward:show.action";
	}
	
	@RequestMapping("/update.action")
	public String update(HttpServletRequest request) throws ServletException,IOException {
		Integer id=Integer.parseInt(request.getParameter("toselectedid").toString());
		String name=request.getParameter("toselectedname").toString();
		//Double pricetemp=Double.parseDouble(request.getParameter("toselectedprice").toString());
		BigDecimal price=new BigDecimal(request.getParameter("toselectedprice").toString());
		String tempDate=request.getParameter("toselectedproduceTime").toString();
		java.sql.Timestamp produceTime=java.sql.Timestamp.valueOf(tempDate);
		String madeFactory=request.getParameter("toselectedmadeFactory").toString();
		TbProduct product=new TbProduct(id,name, price, produceTime, madeFactory);
		//System.out.println(product.toString());
		service.updateByPrimaryKey(product);
		return "forward:show.action";
	}
	
	@RequestMapping("/delete.action")
	public String delete(Integer id){
		service.deleteByPrimaryKey(id);
		return "forward:show.action";
	}
	
}
